//
//  MPMoneyController.m
//  MarkPlatform
//
//  Created by xiao6 on 2017/12/18.
//  Copyright © 2017年 AT. All rights reserved.
//

#import "MPMoneyController.h"
#import "MPMoneyRecordController.h"
#import "MPWalletModel.h"
#import "MPBankBindController.h"

@interface MPMoneyController ()<UITextFieldDelegate> {
    
}
@property (nonatomic, strong) UIView *moneyView;
@property (nonatomic, strong) MPWalletModel *walletInfo;
@property (weak, nonatomic) IBOutlet UIView *colorView;
@property (weak, nonatomic) IBOutlet UILabel *balanceLabel;
@property (weak, nonatomic) IBOutlet UILabel *bankNameLabel;
@property (weak, nonatomic) IBOutlet UITextField *cashAmountField;
@property (nonatomic, assign) BOOL isHaveDian;

@end

@implementation MPMoneyController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.hidden = YES;
    [self setupViews];
    [self setupRefresh:self.tableView option:ATHeaderRefresh|ATHeaderAutoRefresh];
    self.refreshDidAppear = YES;
    self.cashAmountField.delegate = self;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}


- (void)headerRefreshing {
    [super headerRefreshing];
    
    [MPHttpTool POST:@"business/individual/queryWallet"
              params:@{@"userID" : SafeDicObj([ATLocal user].userId)}
             success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                 self.walletInfo = [MPWalletModel modelWithJSON:result.data];
                 NSLog(@"%@", self.walletInfo);
                 self.balanceLabel.text = [NSString stringWithFormat:@"%.2f",self.walletInfo.amount];
                 if (self.walletInfo.cardInfo.length) {
                     self.bankNameLabel.text = self.walletInfo.cardInfo;
                 }
                 else {
                     self.bankNameLabel.text = @"未绑定";
                 }
                 [self endRefresh:NO];
             } failure:ATDefaultFailure];
}
#pragma mark - delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    /*
     * 不能输入.0-9以外的字符。
     * 设置输入框输入的内容格式
     * 只能有一个小数点
     * 小数点后最多能输入两位
     * 如果第一位是.则前面加上0.
     * 如果第一位是0则后面必须输入点，否则不能输入。
     */
    // 判断是否有小数点
    if ([textField.text containsString:@"."]) {
        self.isHaveDian = YES;
    }else{
        self.isHaveDian = NO;
    }
    
    if (string.length > 0) {
        
        // 当前输入的字符
        unichar single = [string characterAtIndex:0];
        
        // 不能输入.0-9以外的字符
        if (!((single >= '0' && single <= '9') || single == '.')) {
            return NO;
        }

        // 只能有一个小数点
        if (self.isHaveDian && single == '.') {
            return NO;
        }
        
        // 如果第一位是.则前面加上0.
        if ((textField.text.length == 0) && (single == '.')) {
            textField.text = @"0";
        }
        
        // 如果第一位是0则后面必须输入点，否则不能输入。
        if ([textField.text hasPrefix:@"0"]) {
            if (textField.text.length > 1) {
                NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
                if (![secondStr isEqualToString:@"."]) {
                    return NO;
                }
            }else{
                if (![string isEqualToString:@"."]) {
                    // 第二个字符需要是小数点
                    return NO;
                }
            }
        }
        
        // 小数点后最多能输入两位
        if (self.isHaveDian) {
            NSRange ran = [textField.text rangeOfString:@"."];
            // 由于range.location是NSUInteger类型的，所以这里不能通过(range.location - ran.location)>2来判断
            if (range.location > ran.location) {
                if ([textField.text pathExtension].length > 1) {
                    return NO;
                }
            }
        }
    }
    return YES;
}


#pragma mark - action
- (IBAction)didClickRightItem:(id)sender {
    [self.navigationController pushViewController:[MPMoneyRecordController vcWithWalletId:self.walletInfo.Id] animated:YES];
}
- (IBAction)didClickBackButton:(id)sender {
    [self goBack];
}
- (IBAction)selectBank:(id)sender {
    MPBankModel *bankModel = [MPBankModel new];
    bankModel.name = self.walletInfo.cardInfo;
    bankModel.code = self.walletInfo.bankCode;
    bankModel.idCard = self.walletInfo.idCard;
    bankModel.card = self.walletInfo.bankCard;
    bankModel.tel = self.walletInfo.bankTel;
    bankModel.userName = self.walletInfo.bankUserName;
    [self.navigationController pushViewController:[MPBankBindController vcWithModel:bankModel] animated:YES];
}
- (IBAction)didClickGetCashAll:(id)sender {
    self.cashAmountField.text = [NSString stringWithFormat:@"%.2f", self.walletInfo.amount];
}
- (IBAction)getCash:(id)sender {
    CGFloat amount = [self.cashAmountField.text doubleValue];
    if (amount > self.walletInfo.amount) {
        [MBProgressHUD showMessage:[NSString stringWithFormat:@"您的余额不足%.2f", amount]];
        return;
    }
    if (!self.walletInfo) {
        [MBProgressHUD showMessage:@"您尚未绑定银行卡"];
        return;
    }
    [MBProgressHUD showWithCompletion:^(MBProgressHUD *hud) {
        [MPHttpTool POST:@"business/wallet/enchashment"
                  params:@{@"walletID" : SafeDicObj(self.walletInfo.Id), @"amount" : @(amount)}
                 success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                     [self headerRefreshing];
                     [hud hideWithMessage:@"提现成功" completion:nil];
                 } failure:ATHttpFailureWithHud(hud)];
    }];
}

#pragma mark - privite
- (void)setupViews {
    [self.view addSubview:self.moneyView];
    // 添加渐变色
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithRGB:0xfc435b].CGColor, (__bridge id)[UIColor colorWithRGB:0xf97e6d].CGColor];
    gradientLayer.locations = @[@0.1, @1.0];
    gradientLayer.startPoint = CGPointMake(0.5, 0);
    gradientLayer.endPoint = CGPointMake(0.5, 1.0);
    CGRect rect = self.colorView.bounds;
    rect.size.width = SCREEN_WIDTH;
    gradientLayer.frame = rect;
    [self.colorView.layer insertSublayer:gradientLayer atIndex:0];
    
    [self.moneyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(self.mas_topLayoutGuide);
    }];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - getters
- (UIView *)moneyView {
    if (!_moneyView) {
        _moneyView = [[NSBundle mainBundle] loadNibNamed:@"MPMoneyView" owner:self options:nil][0];
        _moneyView.backgroundColor = self.view.backgroundColor;
    }
    return _moneyView;
}



@end
